let resultU = false;
let resultP = false;

function changeUsername() {
    let username = document.getElementById("username").value;
    let reg = /^[a-zA-Z]\w{5,15}$/;
    if (reg.test(username)) {
        resultU = true;
        document.getElementById("u_tishi").innerHTML = "你输入正确";
        document.getElementById("u_tishi").style.color = "green";
    } else {
        resultU = false;
        document.getElementById("u_tishi").style.color = "red";
        document.getElementById("u_tishi").innerHTML = "你输入不符合规范";
    }

}

function checkPassword() {
    let password = document.getElementById("password").value;
    let reg = /^[a-zA-Z]\w{5,15}$/;
    if (reg.test(password)) {
        resultP = true;
        document.getElementById("p_tishi").innerHTML = "你输入正确";
        document.getElementById("p_tishi").style.color = "green";
    } else {
        resultP = false;
        document.getElementById("p_tishi").style.color = "red";
        document.getElementById("p_tishi").innerHTML = "你输入不符合规范";
    }
}

function judge() {
    if (resultP && resultU) {
        return true;
    }
    return false;
}

function flushImg(e) {
    // console.log(document.getElementById("code"))
    // document.getElementById("code").style.src = "/code?date=" + Math.random();
    $(e).attr("src", "/code?date=" + Math.random());
}

function toRegisterPage() {
    // window.location.href = "/back/userRegiter.jsp";
    window.open("/back/userRegiter.jsp", "_blank");
}

$(function () {
    // sessionStorage
    let id = localStorage.getItem("userid");
    console.log(id + "--------")
    if (id != null) {//如果id不为空，则需要进行查询,则表示编辑，否则是属于新增
        findByUserId(id);
    }

})

function findByUserId(id) {
    $.ajax({
        url: '/UserFindByUserIdServlet',//这里的注册代表编辑和新增连个功能
        data: {id: id},
        type: 'get',
        dataType: 'json',
        success: function (data) {
            console.log(data);
            setData(data[0]);
        }
    })

}

function setData(data) {
    $("#username").val(data.username);
    $("#username").attr("readonly", true);
    $("#password").val(data.password);
}

function save() {

    if (judge()) {
        let id = localStorage.getItem("userid");
        $.ajax({
            url: '/UserRegiterServlet',//这里的注册代表编辑和新增连个功能
            data: {
                id: id,
                username: $("#username").val(),
                password: $("#password").val(),
                code: $("#code").val()
            },
            type: 'post',
            dataType: 'json',
            success: function (data) {
                console.log(data)
                if (data[0].code == 1) {
                    if (id != null) {
                        $("#right").load("/back/userFindAll.jsp");
                        localStorage.setItem("userid", null);
                    } else {
                        window.open("/back/userLogin.jsp");
                    }

                }
            }
        })
    }
}
